<?php

/**
 * Main controller
 * @return void
 * @author Pablo
 * @since 1.0 
 */
function blg_cnt_main(){
	global $_VIEWS, $_CSS_STACK;
	
	$_URL= blg_get_url_parts();
	
	/*********************************************************
	 * 						CSS FILES
	 *********************************************************/
	
	if($_VIEWS->css_exists($_URL->page)){
		header("Content-type: text/css; charset=utf-8");
		echo compress_css(blg_view($_URL->page, null, CONTEXT_CSS));
		return TRUE;
	}
	
	/*********************************************************
	 * 						JS FILES
	 *********************************************************/
	
	if($_VIEWS->js_exists($_URL->page)){
		header("Content-type: application/x-javascript; charset=utf-8");
		echo blg_view($_URL->page, null, CONTEXT_JS);		
		return TRUE;
	}	
	
	/*********************************************************
	 * 						  PAGES
	 *********************************************************/
	
	if(FALSE!==($url=$_VIEWS->page_exists($_URL->pages))){		
		if(TRUE===($urlto=blg_check_access($url->page))){			
			blg_menu_init();		
			echo blg_view($url->page, array(PAGE_URL_VARS => $url), CONTEXT_HTML);
			return TRUE;
		}
		forward($urlto);
	}
	
	/*********************************************************
	 * 						  ACTIONS
	 *********************************************************/
	
	if($_VIEWS->action_exists($_URL->page)){
		if(TRUE===($urlto=blg_check_access($_URL->page))){				
			echo blg_action($_URL->page, NULL, CONTEXT_ACTION);
			return TRUE;
		}
		forward($urlto);
	}
	
	/*********************************************************
	 * 						  SERVER FILE
	 *********************************************************/
	
	if($_VIEWS->file_exists($_URL->page)){		
		$file= file_url_to_path($_URL->page);
		
		$force_download= (blg_get_input('download', FALSE)!==FALSE);
		$mime= blg_file_get_mime_ext(blg_get_filename_extension($file));
		 		 
		// Set headers
		header("Cache-Control: public");
		header("Content-Description: File Transfer");
		if($force_download)
			header("Content-Disposition: attachment; filename=".basename($file));
		header("Content-Type: ".$mime);
		header("Content-Transfer-Encoding: binary");
		    
		// Read the file from disk
		readfile($file);	
		
		exit();
	}
	elseif(blg_filename_is_image(array_pop($_URL->pages))){		
		$file= blg_get_site_path().'_graphics'.DS.'mod'.DS.'error'.DS.'image.jpg';
		
		$mime= blg_file_get_mime_ext(blg_get_filename_extension($file));
		 		 
		// Set headers
		header("Cache-Control: public");
		header("Content-Description: File Transfer");
		header("Content-Type: ".$mime);
		header("Content-Transfer-Encoding: binary");
		    
		// Read the file from disk
		readfile($file);	
		
		exit();		
	}
	
	/*********************************************************
	 * 						  ELSE
	 *********************************************************/	
	
	return FALSE;
}
